package controller

import (
	"github.com/mjiulee/lego"
	"strconv"

	//"github.com/mjiulee/lego/utils"
	"github.com/valyala/fasthttp"

	. "saas_sys_base/modules/system/service"
)

func init() {
	vc := new (HomeViewCtrl)
	_ctrlList = append(_ctrlList, vc)
}

/* ************************************************************************************ */
/* 类型定义 */
type HomeViewCtrl struct {
	service     SysHomeService
	userService SysUserService
}

func (vc *HomeViewCtrl) CtrlInfo() string {
	return "HomeViewCtrl"
}

func (vc *HomeViewCtrl) RoutInit() {
	lego.GET("/", vc.Index, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/home/index", vc.Index, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/admin/home/console", vc.Console, lego.LEGO_SESSION_TYPE_ADMIN, false)

	lego.POST("/admin/home/initmenu", vc.InitMenu, lego.LEGO_SESSION_TYPE_ADMIN, false)
}

/* 首页
 * params:
 */
func (vc *HomeViewCtrl) Index(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		// 获取平台菜单 资源
		//userid := lego.SessionGetKeyIntVal("user_id", ctx)
		userid, _ := strconv.ParseInt(lego.SessionGetKeyVal("user_id", ctx).(string), 10, 64)
		user, profile := vc.userService.GetSysUserById(userid)
		data["UserName"] = profile.UserName
		menus := vc.service.GetUserRoleMenu(user, profile)
		data["menus"] = menus
		break
	}
	ctxExt.HTML("system/view/Home/home.html", data)
	return
}

/* 首页
 * params:
 */
func (vc *HomeViewCtrl) Console(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		// 统计订单信息
		data["user_today"] = vc.service.GetTodayNewUser()
		data["user_total"] = vc.service.GetTotalUser()

		data["driver_online"] = vc.service.GetOnLineDriver()
		data["driver_total"] = vc.service.GetTotaldriver()

		data["order_today"] = vc.service.GetTodayOrder()
		data["order_total"] = vc.service.GetTotalOrder()

		data["locations"] = vc.service.GetDriverLocations()
		break
	}
	ctxExt.HTML("system/view/Home/console.html", data)
	return
}

/* 首页
 * params:
 */
func (vc *HomeViewCtrl) InitMenu(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := "success"

	for {
		// 统计订单信息
		err := vc.service.InitMenu()
		if err != nil {
			code = -1
			msg = err.Error()
		}
		break
	}
	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}
